package com.maycur.taskdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.maycur.taskdemo.listener.InvoiceEventListener;
import com.maycur.taskdemo.listener.OrderEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@RestController
public class HelloWorld {
    private static Logger log = LoggerFactory.getLogger(HelloWorld.class);

    @RequestMapping("/hello")
    public String Hello(String name) {
        return "Hello " + name;
    }


    @GetMapping("startAsyncEvent")
    public void testProc1(){
        log.info( "test starting ... ");
        //        JDK提供的线程池类
        ThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(5);
        threadPoolExecutor.setMaximumPoolSize(10);
        threadPoolExecutor.setKeepAliveTime(1, TimeUnit.SECONDS);
        threadPoolExecutor.allowCoreThreadTimeOut(false);
        AsyncEventBus aeb = new AsyncEventBus("orderEventBus",threadPoolExecutor);
        aeb.register(new OrderEventListener());

//      新建一个事件消息对象
        JSONObject msg = new JSONObject();
        msg.put("orderNo", "orderNo000001");
        msg.put("userNo", "ochsaofhdhfodhfos00");
//      咱们来使用一个线程去发送事件消息
        Thread t1 = new Thread(()->{
            int i = 0;
            while (i < 100) {
                i++;
                try {
//                    发送事件消息
                    aeb.post(msg);
                    log.info("检查异步");
                } catch (Exception e) {
                  log.error("",e);
                }
            }
        });

        t1.start();
    }

    @GetMapping("startEvent")
    public void testProc2(){
        log.info( "test starting ... ");
        EventBus invoiceEventBus = new EventBus("InvoiceEventListener");
        invoiceEventBus.register( new InvoiceEventListener());
//      咱们来使用一个线程去发送事件消息
        Thread t1 = new Thread(()->{
            int i = 0;
            while (i < 100) {
                i++;
                try {
                    invoiceEventBus.post("发票信息");
                } catch (Exception e) {
                    log.error("",e);
                }
            }
        });

        t1.start();
    }
}
